#### Adapted by Donielle Dixon for NU MPPA 405

####  Set your working directory and bring in your .csv file
####  Name your data 'GSS2016'
setwd('C:/Home/Documents/Northwestern/405')
GSS2016 <- read.csv('GSS2016.csv', header=TRUE)

# Recode income variable (three levels)

GSS2016$increc <- factor(GSS2016$income16,
                         levels = c(1,2.3),
                         labels = c("Lower Class", "Middle Class" , "Upper Class"))

GSS2016$increc <- NA
GSS2016$increc[GSS2016$income16<=17] <- "Lower Class"]
GSS2016$increc[which(GSS2016$income16>=18 & GSS2016$income16=21)] <- "Middle Class"
GSS2016$increc[which(GSS2016$income16>=22 & GSS2016$income16=26)] <- "Upper Class"

table(GSS2016$increc, GSS2016$income16, useNA="always")

# Recode variable on health status (four levels)

GSS2016$health <- factor(GSS2016$health,
                         levels = c(1,2,3,4),
                         labels = c("Excellent", "Good" , "Fair", "Poor"))

# Run the below line to use the 'gmodles' package 
#install.packages("gmodels") # Install the package to be used for the following example.

library("gmodels") # Attach the package to be used for the following example.

# Produce a full contingency table.

CrossTable(GSS2016$increc, GSS2016$health, prop.chisq = FALSE, prop.t = FALSE)  

detach("package:gmodels") # Detach the package "gmodels."

#Run the chi-square test and store the information as an object in the workspace.

increc.health.chi <- chisq.test(GSS2016$income16, GSS2016$health)

# Pull and show observed frequencies from the chisq.test object.

increc.health.chi$observed 

# Pull from the chisq.test object just created and present expected frequencies.

increc.health.chi$expected 

#Produce a table with all of the main results of the chi-square test of independence in the output window.

increc.health.chi 


